<?php
session_start();
require 'database.php';

$error_message = '';
$success_message = '';

// 处理密码重置请求
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $user_id = trim($_POST['user_id'] ?? '');
    $id_number = trim($_POST['id_number'] ?? '');
    $new_password = trim($_POST['new_password'] ?? '');
    $confirm_password = trim($_POST['confirm_password'] ?? '');

    if (empty($user_id) || empty($id_number) || empty($new_password) || empty($confirm_password)) {
        $error_message = '请填写所有必填字段';
    } elseif ($new_password !== $confirm_password) {
        $error_message = '两次输入的密码不一致';
    } elseif (strlen($new_password) < 6) {
        $error_message = '新密码长度至少为6位';
    } else {
        try {
            // 验证用户ID和身份证号
            $sql = "SELECT user_id, name FROM staff WHERE user_id = ? AND id_number = ? AND serving = TRUE";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param('ss', $user_id, $id_number);
            $stmt->execute();
            $result = $stmt->get_result();

            if ($result->num_rows === 1) {
                $user = $result->fetch_assoc();

                // 更新密码
                $password_hash = password_hash($new_password, PASSWORD_DEFAULT);
                $update_sql = "UPDATE staff SET password_hash = ?, updated_at = CURRENT_TIMESTAMP WHERE user_id = ?";
                $update_stmt = $conn->prepare($update_sql);
                $update_stmt->bind_param('ss', $password_hash, $user_id);

                if ($update_stmt->execute()) {
                    $success_message = "密码重置成功！您现在可以使用新密码登录系统";

                    // 记录密码重置日志
                    error_log("Password reset successful for user: $user_id (" . $user['name'] . ")");
                } else {
                    $error_message = '密码更新失败，请稍后重试';
                }
            } else {
                $error_message = '用户ID或身份证号不正确，请检查后重试';
            }
        } catch (Exception $e) {
            $error_message = '系统错误，请稍后重试';
            error_log('Password reset error: ' . $e->getMessage());
        }
    }
}

$page_title = '修改密码 - 考务管理系统';
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $page_title; ?></title>
    <link rel="stylesheet" href="css/style.css">
</head>
<body>
    <div class="login-container">
        <div class="login-card">
            <div class="login-header">
                <h1 class="login-title">修改登录密码</h1>
                <p class="login-subtitle">请使用身份证号验证身份后重置密码</p>
            </div>

            <?php if ($success_message): ?>
                <div class="alert alert-success">
                    <?php echo htmlspecialchars($success_message); ?>
                </div>
                <div class="form-group">
                    <a href="index.php" class="btn btn-primary w-100">返回登录页面</a>
                </div>
            <?php else: ?>
                <?php if ($error_message): ?>
                    <div class="alert alert-error">
                        <?php echo htmlspecialchars($error_message); ?>
                    </div>
                <?php endif; ?>

                <form method="POST" action="reset_password.php" id="resetForm">
                    <div class="form-group">
                        <label for="user_id" class="form-label">OA登录账号</label>
                        <input
                            type="text"
                            id="user_id"
                            name="user_id"
                            class="form-control"
                            placeholder="请输入您的OA登录账号"
                            value="<?php echo htmlspecialchars($_POST['user_id'] ?? ''); ?>"
                            required
                            autofocus
                        >
                    </div>

                    <div class="form-group">
                        <label for="id_number" class="form-label">身份证号</label>
                        <input
                            type="text"
                            id="id_number"
                            name="id_number"
                            class="form-control"
                            placeholder="请输入您的身份证号"
                            value="<?php echo htmlspecialchars($_POST['id_number'] ?? ''); ?>"
                            maxlength="18"
                            required
                        >
                    </div>

                    <div class="form-group">
                        <label for="new_password" class="form-label">新密码</label>
                        <input
                            type="password"
                            id="new_password"
                            name="new_password"
                            class="form-control"
                            placeholder="请输入新密码（至少6位）"
                            minlength="6"
                            required
                        >
                    </div>

                    <div class="form-group">
                        <label for="confirm_password" class="form-label">确认新密码</label>
                        <input
                            type="password"
                            id="confirm_password"
                            name="confirm_password"
                            class="form-control"
                            placeholder="请再次输入新密码"
                            minlength="6"
                            required
                        >
                    </div>

                    <div class="form-group">
                        <button type="submit" class="btn btn-primary w-100">重置密码</button>
                    </div>
                </form>

                <div class="form-group">
                    <a href="index.php" class="btn w-100" style="text-align: center;">返回登录页面</a>
                </div>
            <?php endif; ?>

            <div class="text-center mt-3">
                <p style="color: var(--text-secondary); font-size: 12px;">
                    请确保输入正确的身份证号码<br>
                    新密码将使用安全加密方式存储
                </p>
            </div>
        </div>
    </div>

    <script>
        // 表单验证
        document.getElementById('resetForm')?.addEventListener('submit', function(e) {
            const userId = document.getElementById('user_id').value.trim();
            const idNumber = document.getElementById('id_number').value.trim();
            const newPassword = document.getElementById('new_password').value;
            const confirmPassword = document.getElementById('confirm_password').value;

            if (!userId) {
                alert('请输入OA登录账号');
                document.getElementById('user_id').focus();
                e.preventDefault();
                return false;
            }

            if (!idNumber) {
                alert('请输入身份证号');
                document.getElementById('id_number').focus();
                e.preventDefault();
                return false;
            }

            // 简单的身份证号格式验证
            if (!/^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/.test(idNumber)) {
                alert('身份证号格式不正确');
                document.getElementById('id_number').focus();
                e.preventDefault();
                return false;
            }

            if (newPassword.length < 6) {
                alert('新密码长度至少为6位');
                document.getElementById('new_password').focus();
                e.preventDefault();
                return false;
            }

            if (newPassword !== confirmPassword) {
                alert('两次输入的密码不一致');
                document.getElementById('confirm_password').focus();
                e.preventDefault();
                return false;
            }

            return true;
        });

        // 密码强度提示
        document.getElementById('new_password')?.addEventListener('input', function() {
            const password = this.value;
            const strength = document.getElementById('password-strength') ||
                           document.createElement('div');

            if (!document.getElementById('password-strength')) {
                strength.id = 'password-strength';
                strength.style.fontSize = '12px';
                strength.style.marginTop = '5px';
                this.parentNode.appendChild(strength);
            }

            if (password.length < 6) {
                strength.textContent = '密码长度至少6位';
                strength.style.color = 'var(--error-red)';
            } else if (password.length < 8) {
                strength.textContent = '密码强度：弱';
                strength.style.color = 'var(--warning-orange)';
            } else if (/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/.test(password)) {
                strength.textContent = '密码强度：强';
                strength.style.color = 'var(--success-green)';
            } else {
                strength.textContent = '密码强度：中';
                strength.style.color = 'var(--primary-blue)';
            }
        });
    </script>
</body>
</html>